<template>
    <el-dropdown
        trigger="click"
        @command="handleSetLanguage">
        <span class="el-dropdown-link lang-text">
            <span v-if="language === 'cn'">中文</span>
            <span v-if="language === 'en'">English</span>
            <em class="el-icon-arrow-down el-icon--right"/>
        </span>
        <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
                :disabled="language==='cn'"
                command="cn">中文</el-dropdown-item>
            <el-dropdown-item
                :disabled="language==='en'"
                command="en">English</el-dropdown-item>
        </el-dropdown-menu>
    </el-dropdown>
</template>
<script>
import { setLanguage } from 'common/src/api/session'

export default {
    name: 'LangSelect',
    inject: ['reload'],
    data() {
        return {
            currentLang: this.$store.getters.language
        }
    },
    computed: {
        language() {
            return this.$store.getters.language
        }
    },
    created() {
        this.setLanguage(this.language, 'noreload')
    },
    methods: {
        handleSetLanguage(lang) {
            this.setLanguage(lang)
        },
        setLanguage(lang, noReload) {
            setLanguage({
                language: lang
            }).then(res => {
                if (res.code === 200) {
                    this.$i18n.locale = lang// 给前端使用
                    this.$store.dispatch('setLanguage', lang)// 给后端使用
                    if (!noReload) {
                        this.$message({
                            message: this.language == 'en' ? 'switch language success' : '切换语言成功',
                            type: 'success'
                        })
                        this.reload()
                    }
                } else {
                    this.$message({
                        message: res.msg,
                        type: 'error'
                    })
                }
            })
        }
    }
}
</script>
<style lang="scss" scoped>
  .lang-text {
    cursor: pointer;
    color: #3A7FE8;
  }
  .el-dropdown-link {
    cursor: pointer;
    color: #3A7FE8;
  }
</style>
